package com.ruoyi.feike.service.impl;

import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.DealerInformation;
import com.ruoyi.feike.domain.ParkingLocation;
import com.ruoyi.feike.domain.Plm;
import com.ruoyi.feike.domain.vo.ParkingLocationVO;
import com.ruoyi.feike.mapper.DealerInformationMapper;
import com.ruoyi.feike.mapper.ParkingLocationMapper;
import com.ruoyi.feike.mapper.PlmMapper;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IParkingLocationService;
import com.ruoyi.feike.service.IPlmService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * feikeService业务层处理
 *
 * @author zmh
 * @date 2022-07-05
 */
@Service
public class ParkingLocationServiceImpl implements IParkingLocationService
{
    private static final Logger log = LoggerFactory.getLogger(ParkingLocationServiceImpl.class);
    @Autowired
    private ParkingLocationMapper parkingLocationMapper;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private PlmMapper plmMapper;

    @Autowired
    private IPlmService iPlmService;

    @Autowired
    private IAnnualReviewyService annualReviewyService;



    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public ParkingLocation selectParkingLocationById(String id)
    {
        return parkingLocationMapper.selectParkingLocationById(id);
    }

    /**
     * 查询feike列表
     *
     * @param parkingLocation feike
     * @return feike
     */
    @Override
    public List<ParkingLocation> selectParkingLocationList(ParkingLocation parkingLocation)
    {
        return parkingLocationMapper.selectParkingLocationList(parkingLocation);
    }

    @Override
    public List<ParkingLocation> selectParkingLocationByIds(List<String> ids)
    {
        return parkingLocationMapper.selectParkingLocationByIds(ids);
    }

    /**
     * 连接连接dealerinformation查询数据
     *
     * @param parkingLocation feike
     * @return feike
     */
    @Override
    public List<ParkingLocationVO> selectParkingLocationListANDplm(ParkingLocationVO parkingLocation)
    {
        return parkingLocationMapper.selectParkingLocationListANDplm(parkingLocation);
    }

    /**
     * 新增feike
     *
     * @param parkingLocation feike
     * @return 结果
     */
    @Override
    public int insertParkingLocation(ParkingLocation parkingLocation)
    {
        return parkingLocationMapper.insertParkingLocation(parkingLocation);
    }

    /**
     * 修改feike
     *
     * @param parkingLocation feike
     * @return 结果
     */
    @Override
    public int updateParkingLocation(ParkingLocation parkingLocation)
    {
        return parkingLocationMapper.updateParkingLocation(parkingLocation);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteParkingLocationByIds(String[] ids)
    {
        return parkingLocationMapper.deleteParkingLocationByIds(ids);
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteParkingLocationById(String id)
    {
        return parkingLocationMapper.deleteParkingLocationById(id);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<ParkingLocation> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new CustomException("导入经销商信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 导入前清表一次
        parkingLocationMapper.deletePklBy();
        for (ParkingLocation stu : userList)
        {
            try
            {
                stu.setId(IdUtils.simpleUUID());

                this.insertParkingLocation(stu);
                successNum++;
                successMsg.append("<br/>" + successNum + "、经销商 " + stu.getDealernamecn() + " 导入成功");

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、经销商 " + stu.getDealernamecn() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询全部
     * @return
     */
    @Override
    public List<Map> selectParkingLocationLists() {
        List<Map> mapList=new ArrayList<>();
        List<Plm> plmList = plmMapper.selectPlmLists();
        if(plmList!=null&&plmList.size()>0){
            for (Plm plm : plmList) {
                Map map=new HashMap();
                List<DealerInformation> dealerInformationList = dealerInformationMapper.selectDealerInformationByDealerName(plm.getDealernamecn());
                String groupName = dealerInformationList.get(0).getGroupName();
                if(!StringUtils.isEmpty(groupName)){
                    map.put("groupName",groupName);
                }
                map.put("dealernamecn",plm.getDealernamecn());
                mapList.add(map);
            }
        }
        return mapList;
    }

    @Override
    public Map getFlagByDealerNameAndType(Map map) {
        System.out.println("map===="+map);
        String dealerName = (String) map.get("dealerName");
        String type = (String) map.get("type");
        Map content=new HashMap();
        if (!StringUtils.isEmpty(type) && "二网".equals(type)){
            // 获取数量
            Map mapObj = parkingLocationMapper.getFlagByDealerNameAndType(dealerName,type);
            Long num1 = (Long) mapObj.get("num");
            System.out.println("num1=="+num1);
            // int i1 = Integer.parseInt(num);

            // 与 允许交保证金使用二网数 比较
            Map mapObj2 = plmMapper.getFlagByDealerName(dealerName);
            Integer num2 = (Integer) mapObj2.get("num");
            System.out.println("num2=="+num2);
            // int i2 = Integer.parseInt(num2);

            if (num1>=num2){
                content.put("content","经销商二网数量已达上线");
            }
        }
        return content;
    }

    /**
     * 根据业务规则修改status状态
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int updateParkingLocationStatus()
    {
        ParkingLocation parkingLocation = new ParkingLocation();
        List<ParkingLocation> parkingLocations = this.selectParkingLocationList(parkingLocation);
        //每次运行规则时，除失效网点外，全部重置为启用，再运行以下规则
        for(ParkingLocation plc : parkingLocations){
            if(!plc.getStatus().equals("2")){
                ParkingLocation parkingLocation1 = new ParkingLocation();
                BeanUtils.copyProperties(plc,parkingLocation1);
                plc.setStatus("0");
                this.updateParkingLocation(plc);
                annualReviewyService.saveDbLog("3","修改",null,null,parkingLocation1,plc,"同步状态");


            }
        }
        for(ParkingLocation pl : parkingLocations){
            ParkingLocation pl1 = new ParkingLocation();
            BeanUtils.copyProperties(pl,pl1);
//            Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(new Date().toString());
            Date parse;
            //实现将字符串转成⽇期类型(格式是yyyy-MM-dd)
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            try {
                parse = (Date)dateFormat.parseObject(dateFormat.format(new Date()));
            } catch (Exception e) {
                parse = null;
            }

            if(StringUtils.isNotNull(pl.getDuedate())) {
//                Date date = DateUtils.parseGeLing(pl.getDuedate().toString(), "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                if (pl.getDuedate().before(parse)) {//表duedate日期是否在当前日期之前，为true代表已过
                    //代表过期了，就修改状态为失效
                    pl.setStatus("2");
                    this.updateParkingLocation(pl);
                    annualReviewyService.saveDbLog("3","修改",null,null,pl1,pl,"同步状态");

                }
            }
        }
        //根据规则对于已支付二网保证金为0的二网：当经销商数据库2“允许无偿使用二网数”<数据库1已支付二网保证金为0的二网数，
        // 按照添加时间顺序依次禁用溢出部分
        ParkingLocation parkingLocationTwo = new ParkingLocation();
        parkingLocationTwo.setType("二网");
        parkingLocationTwo.setTwondtierdeposit(new BigDecimal(0));
        parkingLocationTwo.setStatus("0");
        List<ParkingLocation> parkingTwo = this.selectParkingLocationList(parkingLocationTwo);

        for(ParkingLocation parkingNewTwo : parkingTwo){
            ParkingLocation pl2 = new ParkingLocation();
            BeanUtils.copyProperties(parkingNewTwo,pl2);
            Plm plm = new Plm();
            plm.setDealernamecn(parkingNewTwo.getDealernamecn());
            Plm plm1 = new Plm();
            List<Plm> plms = iPlmService.selectPlmList(plm);
            try {
                 plm1 = plms.get(0);//查出对应经销商的plm数据
            }catch (Exception e){
                throw  new BaseException(parkingNewTwo.getDealernamecn() +"不存在");
            }

            ParkingLocation parkingLocationThree = new ParkingLocation();
            parkingLocationThree.setType("二网");
            parkingLocationThree.setTwondtierdeposit(new BigDecimal(0));
            parkingLocationThree.setStatus("0");
            parkingLocationThree.setDealernamecn(parkingNewTwo.getDealernamecn());
            //查状态为启用的数据
            List<ParkingLocation> parkingThree = this.selectParkingLocationList(parkingLocationThree);
            //用plm的无偿使用二网数字段比对对应经销商的数据和
            if(plm1.getPermitted2ndtierwithoutdesposit()<parkingThree.size()){
                parkingNewTwo.setStatus("1");
                this.updateParkingLocation(parkingNewTwo);
                annualReviewyService.saveDbLog("3","修改",null,null,pl2,parkingNewTwo,"同步状态");

            }

        }
        //对于已支付二网保证金大于0的二网：当经销商数据库2“允许交保证金使用二网数”<数据库1已支付二网保证金大于0的二网数，
        // 按照添加时间顺序依次禁用溢出部分
        for(ParkingLocation parkingNewTwo : parkingTwo){
            ParkingLocation pl3 = new ParkingLocation();
            BeanUtils.copyProperties(parkingNewTwo,pl3);

            Plm plm = new Plm();
            Plm plm1 = new Plm();
            plm.setDealernamecn(parkingNewTwo.getDealernamecn());
            List<Plm> plms = iPlmService.selectPlmList(plm);
            try {
                plm1 = plms.get(0);//查出对应经销商的plm数据
            }catch (Exception e){
                throw  new BaseException(parkingNewTwo.getDealernamecn() +"不存在");
            }
            ParkingLocation parkingLocationThree = new ParkingLocation();
            parkingLocationThree.setType("二网");
            parkingLocationThree.setStatus("0");
            parkingLocationThree.setDealernamecn(parkingNewTwo.getDealernamecn());
            //查状态为启用的数据
            List<ParkingLocation> parkingThree = parkingLocationMapper.selectParkingLocationListgreaterThanZero(parkingLocationThree);
            //用plm的无偿使用二网数字段比对对应经销商的数据和
            if(plm1.getPermitted2ndtierwithdesposit()<parkingThree.size()){
                parkingNewTwo.setStatus("1");
                this.updateParkingLocation(parkingNewTwo);
                annualReviewyService.saveDbLog("3","修改",null,null,pl3,parkingNewTwo,"同步状态");

            }

        }

        return 1;
    }
}
